from rest_framework import serializers

from goods.models import SKU


# 购物车序列化器， 检验参数使用
class CartSerializer(serializers.Serializer):
    # 定义字段
    sku_id = serializers.IntegerField(label='商品SKU编号', min_value=1)
    count = serializers.IntegerField(label='商品数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    # 校验sku_id 和count
    def validate(self, attrs):
        # 接收参数
        sku_id = attrs['sku_id']
        count = attrs['count']
        # 校验sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')
        # 检查count是否大于库存
        if count > sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化器, 用于查询购物车商品信息
    """
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


# 删除购物车数据的序列化器
class CartDeleteSerializer(serializers.Serializer):
    """
    删除购物车数据序列化器
    """
    sku_id = serializers.IntegerField(label='商品id', min_value=1)

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value


class CartSelectAllSerializer(serializers.Serializer):
    """
    购物车全选
    """
    selected = serializers.BooleanField(label='全选')
